/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.webbucks;

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.*;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.sql.*;
import java.util.List;
import javax.servlet.RequestDispatcher;

/**
 *
 * @author ghaban
 */
public class Manager extends HttpServlet {

    /**
     * Processes requests for both HTTP
     * <code>GET</code> and
     * <code>POST</code> methods.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
    }

   
    /**
     * Handles the HTTP
     * <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        authUser(request, response);
        try {
            List<ProductBean> products = ProductBean.list();
            SupplyBean sb = new SupplyBean();
            List<Ingredient> supply = sb.getIngredients();
            request.setAttribute("products", products);
            request.setAttribute("supply", supply);
            request.getRequestDispatcher("/manage.jsp").forward(request, response);
        } catch (SQLException e) {
            throw new ServletException("Cannot obtain products from DB", e);
        }
        
    }

    /**
     * Handles the HTTP
     * <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        //processRequest(request, response);
        
        checkForms(request,response);
           
        doGet(request, response);     
    }

    
    protected void authUser(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        HttpSession session = request.getSession(false);
        ManagerBean currMan = null;
        if(session != null){
            currMan = (ManagerBean)session.getAttribute("currentSessionUser");
        }
        if(currMan == null || !currMan.isValid()){
        try { 
            ManagerBean man = new ManagerBean();
            man.setUsername(request.getParameter("un")); 
            man.setPassword(request.getParameter("pw")); 
            if (man.isValid()) { 
                session = request.getSession(true);
                session.setAttribute("currentSessionUser",man); 
            } else {
              System.out.println("Auth failed!");  
              request.getRequestDispatcher("/managerLogin.jsp").forward(request, response);
        
            } 
        }
    catch (Exception e) { System.out.println(e); 
    } 
        }
 }
    
    
        protected void checkForms(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        //processRequest(request, response);
 
        String url = "jdbc:mysql://localhost:8889/";
        String dbName = "webbucks";
        String driver = "com.mysql.jdbc.Driver";
        String user = "root"; 
        String pw = "root";
        PreparedStatement ps;
        try {
            Class.forName(driver).newInstance();
            Connection con=DriverManager.getConnection(url+dbName,user,pw);
            String Query = "Select * from price order by name";
            Statement stmt = con.createStatement();
            ResultSet srs = stmt.executeQuery(Query);
            int currentPrice;
            String checked;
            String postedPrice;
            String currentName;
            
            while (srs.next()) {  
             currentName = srs.getString("name");
             currentPrice = srs.getInt("price");
             postedPrice = request.getParameter("price_"+currentName);
             checked = request.getParameter("delete_"+currentName);            
            System.out.println("comparing posted price with current price!");
             if(postedPrice != null && Integer.parseInt(postedPrice) != currentPrice){
                String priceQuery = "update price SET price=" + postedPrice + " where name=\""+currentName+"\"";
                Statement priceStmt = con.createStatement();
                System.out.println(priceQuery);
                priceStmt.executeUpdate(priceQuery);
                priceStmt.close();
                
             }
             if(checked != null){
                String delQuery = "DELETE FROM products where name=\""+currentName+"\"";
                Statement delStmt = con.createStatement();
                delStmt.executeUpdate(delQuery);
                delStmt.close();
                delQuery = "DELETE FROM price where name=\""+currentName+"\"";
                delStmt = con.createStatement();
                delStmt.executeUpdate(delQuery);
                delStmt.close();
             }
            
            }
            con.close();
        }
        catch( Exception e ){
            System.out.println("Something went wrong" + e.toString() );
        }
                try {
            Class.forName(driver).newInstance();
            Connection con=DriverManager.getConnection(url+dbName,user,pw);
            String Query = "Select * from ingredients order by name";
            Statement stmt = con.createStatement();
            ResultSet srs = stmt.executeQuery(Query);

            String currentIngredient;
            String amountToOrder;
            int currentSupply;
            String productName = request.getParameter("add_product");
           // String cleanProductName = productName.replaceAll("\\s","");
            String ingredientList ="";
            String ingredientChosen;
            boolean newProductAdded = false;
            while (srs.next()) {  
             currentIngredient = srs.getString("name");
             currentSupply = srs.getInt("supply");
             ingredientChosen = request.getParameter("add_"+currentIngredient);

             System.out.println("Iterating through ingredients..");
             amountToOrder = request.getParameter(currentIngredient);
             if(amountToOrder != null && currentIngredient != null){
                int updatedValue = currentSupply + Integer.parseInt(amountToOrder); 
                String updateQuery = "UPDATE ingredients SET supply="+updatedValue+" where name=\""+currentIngredient+"\"";
                System.out.println(updateQuery);
                Statement updateStmt = con.createStatement();
                updateStmt.executeUpdate(updateQuery);
                updateStmt.close(); 
             }
             System.out.println("Check productname and ingredient: " + productName + "   "+ ingredientChosen);
             if(productName != null && ingredientChosen != null){
                String updateQuery = "INSERT INTO products(name,ingredient) VALUES(\""+ productName+"\",\""+ingredientChosen+"\")";
                System.out.println(updateQuery);
                Statement updateStmt = con.createStatement();
                updateStmt.executeUpdate(updateQuery);
                updateStmt.close();
                newProductAdded = true;
             }
            }
            if(newProductAdded){
                String updateQuery = "INSERT INTO price(name,price) VALUES(\""+productName+"\",0)";
                System.out.println(updateQuery);
                Statement updateStmt = con.createStatement();
                System.out.println("updatestatement created!");
                updateStmt.executeUpdate(updateQuery);
                System.out.println("Executed Update!");
                updateStmt.close();
                System.out.println("Close update!");
                
                
                System.out.println("adding column to order database...");
                updateQuery = "ALTER TABLE orderstatus ADD "+ productName + " integer DEFAULT 0";
                updateStmt = con.createStatement();
                System.out.println("updatestatement created!");
                updateStmt.executeUpdate(updateQuery);
                System.out.println("Executed Update!");
                updateStmt.close();
                System.out.println("Close update!");
                
            }
            System.out.println("Finished adding product!");
            con.close();
            System.out.println("closed connection to db!");
        }
        catch( Exception e ){
            System.out.println("Something went wrong" + e.toString() );
        }
            if(request.getParameter("logout") != null && request.getParameter("logout").equals("1")){
                HttpSession sess = request.getSession(false);
                if(sess != null){
                sess.invalidate();
                }    
            }
        }
    
    
    
    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
